import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xvideos/assets_tool/images.dart';

class FloatingAiTeachView extends StatefulWidget {
  final Function? tapCallBack;

  const FloatingAiTeachView({super.key, this.tapCallBack});

  @override
  State<StatefulWidget> createState() {
    return _FloatingSignInViewState();
  }
}

class _FloatingSignInViewState extends State<FloatingAiTeachView> {
  final _floatingGlobalKey = GlobalKey();
  double _bottom = 10;
  double _right = 0;
  double _width = 0;

  double get _adSize => 80;

  double get width {
    if (_width == 0) {
      RenderBox? renderBox = _floatingGlobalKey.currentContext?.findRenderObject() as RenderBox?;
      _width = renderBox?.size.width ?? MediaQuery.of(context).size.width;
      _height = renderBox?.size.height ?? MediaQuery.of(context).size.height;
    }
    return _width;
  }

  double _height = 0;

  double get height {
    if (_height == 0) {
      RenderBox? renderBox = _floatingGlobalKey.currentContext?.findRenderObject() as RenderBox?;
      _width = renderBox?.size.width ?? MediaQuery.of(context).size.width;
      _height = renderBox?.size.height ?? MediaQuery.of(context).size.height;
    }
    return _height;
  }

  void _onPanUpdate(DragUpdateDetails details) {
    _right -= details.delta.dx;
    _bottom -= details.delta.dy;
    if (_right > width - _adSize) {
      _right = width - _adSize;
    }
    if (_right < 0) _right = 0;
    if (_bottom > height - _adSize) {
      _bottom = height - _adSize;
    }
    if (_bottom < 0) _bottom = 0;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      key: _floatingGlobalKey,
      child: Stack(
        children: [
          Positioned(
            bottom: _bottom,
            right: _right,
            child: ClipRRect(
              borderRadius: BorderRadius.circular(8),
              child: SizedBox(
                height: _adSize,
                width: _adSize,
                child: GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTapUp: (details) {
                    widget.tapCallBack?.call();
                  },
                  onPanUpdate: (DragUpdateDetails details) {
                    _onPanUpdate(details);
                  },
                  onPanEnd: (details) {
                    // print('onPanEnd${_right}'
                    if (_right > Get.width / 2) {
                      _right = Get.width - _adSize;
                    } else {
                      _right = 0;
                    }
                    setState(() {});
                  },
                  child: Image.asset(
                    'mine_ai_logo.gif'.mineImgPath,
                    width: _adSize,
                  ),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
}
